<template>
  <div>
    <div class="search">
      <input class="search-input" v-model="keywords" type="text" placeholder="输入城市名或拼音">
    </div>
    <div class="search-content" ref="search-content" v-show="keywords">
      <ul>
        <li
          class="item border-bottom"
          v-for="item of list"
          :key="item.id"
          @click="handleCityClick(item.name)"
        >{{ item.name }}</li>
        <li class="item border-bottom" v-show="isShow">没有匹配的数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
import { mapState, mapMutations } from "vuex";
export default {
  name: "CitySearch",
  data() {
    return {
      list: [],
      keywords: "",
      timer: null
    };
  },
  methods: {
    handleCityClick(city) {
      this.changeCity(city);
      this.$router.push("/");
    },
    ...mapMutations(["changeCity"])
  },
  mounted() {
    this.scroll = new Bscroll(this.$refs["search-content"], {
      click: true
    });
    setTimeout(() => {
      // console.log(this.scroll);
      if (!this.scroll) {
        this.scroll = new Bscroll(this.$refs["search-content"], {
          click: true
        });
      } else {
        this.scroll.refresh();
      }
    }, 500);
  },
  props: ["cities"],
  computed: {
    isShow() {
      return !this.list.length;
    }
  },
  watch: {
    keywords() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keywords.trim().length) {
        return (this.list = []);
      }
      this.timer = setTimeout(() => {
        const list = [];
        for (let i in this.cities) {
          this.cities[i].forEach(element => {
            if (
              element.spell.indexOf(this.keywords) > -1 ||
              element.name.indexOf(this.keywords) > -1
            ) {
              list.push(element);
            }
          });
        }
        this.list = list;
      }, 100);
    }
  }
};
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.search {
  padding: 0.1rem;
  background: $bgColor;
  height: 0.72rem;

  .search-input {
    width: 100%;
    height: 0.62rem;
    line-height: 0.62rem;
    border-radius: 0.06rem;
    text-align: center;
    padding: 0 0.1rem;
    box-sizing: border-box;
  }
}

.search-content {
  overflow: hidden;
  position: absolute;
  z-index: 1;
  top: 1.78rem;
  background: #eee;
  left: 0;
  right: 0;
  bottom: 0;

  .item {
    line-height: 0.62rem;
    padding-left: 0.2rem;
    color: 666;
    background: #fff;
  }
}
</style>
